<template>
  <div>
    <div class="close"><img @click="closefn" src="../../assets/img/photo-cancelBtn.png" alt=""></div>
    <div class="fbbox">
      <!-- <head-nav></head-nav> -->
      <div class="fb-t">填写参赛信息</div>
      <div class="fb-list">
        <mt-field placeholder="请输入参赛名称" v-model="csmc"></mt-field>
      </div>
      <div class="fb-list">
        <mt-field placeholder="请输入个人介绍拉票宣言" type="textarea" rows="4" v-model="lpxy"></mt-field>
      </div>
      <div class="upph">
        <div class="chooseImg">
          <div class="page-body-info">
            <div class='hasPh' v-for="(item,index) in tempFilePaths" :key="index">
              <div class="phbox">
                <img :src="item" class="image" />
              </div>
              <div class='clear' @click='clearImg(index)'>×</div>
            </div>
            <div class="chooseBtn">
              <img src="../../assets/img/photo-uploadImgBtn.png">
              <input type="file" accept="image/*" @change="imageFileChange" name="file" ref="inputer" /> <!-- handleFileChange   imageFileChange -->
            </div>
          </div>
          <p class="upTip">最多可上传4张</p>
        </div>
      </div>
      <div class="fb-t">填写联系信息</div>
      <div class="fb-list">
        <mt-field placeholder="请输入姓名" v-model="xm"></mt-field>
      </div>
      <div class="fb-list">
        <mt-field placeholder="请输入联系电话" type="tel" v-model="lxdh"></mt-field>
      </div>
      <!-- <div class="fb-t">请选择地区</div>
      <div class="fb-list">
        <div class="xzdq"><x-address title='' v-model="addressValue" raw-value :list="addressData" value-text-align="left"></x-address></div>
        <div>
          <mt-field placeholder="请输入详细地址" type="textarea" rows="2"></mt-field>
        </div>
      </div> -->

    </div>
    <div class="tj"><button class="tjbtn" @click="releasefn">确认修改</button></div>
  </div>
</template>

<script>
import EXIF from "exif-js";
import api from "@/api/api";
import { Toast, MessageBox } from "mint-ui";
// import { Group, XAddress,ChinaAddressData } from 'vux'

export default {
  props: ["resobj"],
  data() {
    return {
      csmc: "",
      lpxy: "",
      xm: "",
      lxdh: "",
      userid: "",
      // addressData: ChinaAddressData,
      // addressValue: ['北京市', '市辖区', '东城区'],
      // 图片start
      tempFilePaths: [],
      file: "",
      arr: [],
      testph: [],
      compressFrondImage: "", // 压缩之前的图片
      compressEndImage: "" // 压缩之后的图片
      // 图片end
    };
  },
  methods: {
    //关闭页面
    closefn() {
      window.history.back();
      this.$emit("footnavzt", true);
    },
    // 提交表单
    releasefn() {
      let that = this;
      if (this.csmc == "") {
        that.Toastfn("请输入参赛名称", 2000, "");
      } else if (this.lpxy == "") {
        that.Toastfn("请输入个人介绍拉票宣言", 2000, "");
      } else if (this.xm == "") {
        that.Toastfn("请输入姓名", 2000, "");
      } else if (this.lxdh == "") {
        that.Toastfn("请输入联系电话", 2000, "");
      } else if (this.lxdh.length != 11) {
        that.Toastfn("请输入正确的联系电话", 2000, "");
      } else if (this.testph.length == 0) {
        that.Toastfn("请上传图片", 2000, "");
      } else {
        let id = this.$route.query.id;
        let hdId = this.resobj.ID;
        let comName = this.csmc;
        let introduce = this.lpxy;
        let name = this.xm;
        let tel = this.lxdh;
        let userId = this.userid;
        
        api.photoSignUp(
          this,
          hdId,
          comName,
          introduce,
          name,
          tel,
          userId,
          id,
          function(res) {
            let data = res.data;
            if (data.code == 0) {
              
              let data1 = JSON.parse(data.data);
              if (data1.code == 0) {
                //上传图片
                let sid = data1.data;
                if (that.testph.length > 0) {
                  // 有图片
                  let num = 0;
                  // alert(that.testph[num])
                  uploadph();
                  function uploadph() {
                    api.photoUpload(
                      that,
                      that.testph[num],
                      that.userid,
                      sid,
                      "ht",
                      // "2c91a36a605505f5016059d26400024d",
                      "2c912cce66f8543401674e37afd335fd",
                      function(res) {
                        let data = res.data;
                        if (data.code === 0) {
                          num++;
                          if (num === that.testph.length) {
                            MessageBox({
                              title: "提示",
                              message: "修改成功！",
                              showCancelButton: false
                            }).then(action => {
                              that.$router.push("list");
                            });
                            return;
                          }
                          uploadph();
                        } else {
                          Toast({
                            message: "图片上传失败",
                            duraion: 1000
                          });
                        }
                      }
                    );
                  }
                }
              } else {
                that.Toastfn(data1.msg, 2000, "");
              }
            } else {
              that.Toastfn(data.msg, 2000, "");
            }
          }
        );
      }
    },
    clearImg(index) {
      this.tempFilePaths.splice(index, 1);
      var arr = this.tempFilePaths;
      this.tempFilePaths = arr;
      // 对应删除
      this.testph.splice(index, 1);
      var arr2 = this.testph;
      this.testph = arr2;
    },
    //上传图片
    // 图片开始
    /**
     * 图片文件发生变化
     */
    imageFileChange(e) {
      this.file = e.target.files[0];
      if (this.file) {
        if (this.testph.length >= 4) {
          Toast({
            message: "您上传的图片已经够多了",
            duraiton: 1500
          });
          return;
        } else {
          let reader = new FileReader();
          reader.readAsDataURL(this.file);
          reader.onload = e => {
            console.log(e.target);
            this.compressFrondImage = e.target.result;
            this.compressImages(this.compressFrondImage);
          };
        }
      }
    },
    compressImages(res) {
      let defaultImage = {
        width: 1440,
        height: 1080,
        quality: 0.8, // 压缩图片的质量
        orientation: "" // 获取照片方向角属性，用户旋转控制
      };
      var img = new Image();
      img.src = res;
      let initSize = img.src.length;
      img.onload = () => {
        // 方便手机测试
        // alert("压缩之前宽度： " + img.width);
        // alert("压缩之前高度： " + img.height);
        // 方便浏览器测试
        //      alert("压缩之前宽度： " + img.width);
        console.log("压缩之前高度： " + img.height);
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        if (img.width > defaultImage.width) {
          img.height = img.height * (defaultImage.width / img.width);
          img.width = defaultImage.width;
        }
        if (img.height > defaultImage.height) {
          img.width *= defaultImage.height / img.height;
          img.height = defaultImage.height;
        }
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        EXIF.getData(this.file, () => {
          // IMG_FILE为图像数据
          // 是否是iPhone手机，iPhone 拍照之后的压缩是逆时针旋转90，针对iphone做一下处理
          if (navigator.userAgent.match(/iphone/i)) {
            defaultImage.orientation = EXIF.getTag(this.file, "Orientation");
            // translate是平移变换，scale(-1,1)是向左翻转，rotate是顺时针旋转。
            // defaultImage.orientation = 6   // 测试iPhone手机
            // alert("Orientation:" + defaultImage.orientation); // 拍照方向
            switch (Number(defaultImage.orientation)) {
              case 2:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.drawImage(img, 0, 0, img.width, img.height);
                break;
              case 3:
                ctx.rotate((180 * Math.PI) / 180);
                ctx.drawImage(
                  img,
                  -img.width,
                  -img.height,
                  img.width,
                  img.height
                );
                break;
              case 4:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((180 * Math.PI) / 180);
                ctx.drawImage(
                  img,
                  -img.width,
                  -img.height,
                  img.width,
                  img.height
                );
                break;
              case 5:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((90 * Math.PI) / 180);
                ctx.drawImage(img, 0, -img.width, img.height, img.width);
                break;
              case 6:
                canvas.width = img.height;
                canvas.height = img.width;
                ctx.rotate((90 * Math.PI) / 180);
                ctx.drawImage(img, 0, 0, img.width, -img.height);
                break;
              case 7:
                ctx.translate(img.width, 0);
                ctx.scale(-1, 1);
                ctx.rotate((270 * Math.PI) / 180);
                ctx.drawImage(img, -img.height, 0, img.height, img.width);
                break;
              case 8:
                ctx.rotate((270 * Math.PI) / 180);
                ctx.drawImage(img, -img.height, 0, img.height, img.width);
                break;
              default:
                ctx.drawImage(img, 0, 0, img.width, img.height);
            }
          } else {
            ctx.drawImage(img, 0, 0, img.width, img.height);
          }
          var imgUrl = canvas.toDataURL("image/png", defaultImage.quality);
          // 手机端测试
          // alert(
          //   "压缩率：" + ~~(100 * (initSize - imgUrl.length) / initSize) + "%"
          // );
          // alert("压缩之后宽度： " + img.width);
          // alert("压缩之后高度： " + img.height);
          // 浏览器测试
          // console.log("压缩前：" + initSize);
          // console.log("压缩后：" + imgUrl.length);
          console.log(
            "压缩率：" + ~~((100 * (initSize - imgUrl.length)) / initSize) + "%"
          );
          // console.log("压缩之后宽度： " + img.width);
          // console.log("压缩之后高度： " + img.height);
          console.log("压缩之后base64地址");
          console.log(imgUrl);
          //  alert('地址');
          // 压缩之后的base64 图片地址
          this.compressEndImage = imgUrl;
          // that.testph.push(afile);
          this.tempFilePaths.push(imgUrl);
          // 开始base64转formdata格式上传  这个转化formdata有问题
          // function dataURLtoFile(dataurl, filename) {
          //   //将base64转换为文件
          //   var arr = dataurl.split(","),
          //     mime = arr[0].match(/:(.*?);/)[1],
          //     bstr = atob(arr[1]),
          //     n = bstr.length,
          //     u8arr = new Uint8Array(n);
          //   while (n--) {
          //     u8arr[n] = bstr.charCodeAt(n);
          //   }
          //   return new File([u8arr], filename, {
          //     type: mime
          //   });
          // }
          //var blob = dataURLtoFile(imgUrl, "img.jpg");
          function dataURItoBlob(base64Data) {
            var byteString;
            if (base64Data.split(",")[0].indexOf("base64") >= 0)
              byteString = atob(base64Data.split(",")[1]);
            else byteString = unescape(base64Data.split(",")[1]);
            var mimeString = base64Data
              .split(",")[0]
              .split(":")[1]
              .split(";")[0];
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
              ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ia], { type: mimeString });
          }
          var blob = dataURItoBlob(imgUrl); // base64 转formdata

          //结束base64转换

          this.testph.push(blob);

          // TODO 上传图片文件
          this.uploadImage();
        });
      };
    },
    /**
     * 上传图片
     */
    uploadImage: function() {},
    /**
     * 瓦片压缩 正在测试
     */
    imagesCompress: function(img) {
      // 用于压缩图片的canvas
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      // 瓦片canvas
      var tCanvas = document.createElement("canvas");
      var tctx = tCanvas.getContext("2d");

      var initSize = img.src.length;
      var width = img.width;
      var height = img.height;

      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      var ratio;
      if ((ratio = (width * height) / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }

      canvas.width = width;
      canvas.height = height;

      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 如果图片像素大于100万则使用瓦片绘制
      var count;
      if ((count = (width * height) / 1000000) > 1) {
        count = ~~(Math.sqrt(count) + 1); // 计算要分成多少块瓦片

        // 计算每块瓦片的宽和高
        var nw = ~~(width / count);
        var nh = ~~(height / count);

        tCanvas.width = nw;
        tCanvas.height = nh;

        for (var i = 0; i < count; i++) {
          for (var j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );

            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }

      // 进行最小压缩
      var ndata = canvas.toDataURL("image/jpeg", 0.8);

      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~((100 * (initSize - ndata.length)) / initSize) + "%"
      );

      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
    // 图片结束

    // 提示函数
    Toastfn(message, duration, position) {
      Toast({
        message: message,
        duration: duration,
        position: position
      });
    },
    // 详情
    getDetail() {
      let that = this;
      let userId = that.userId;
      let id = this.$route.query.id;
      api.photoInfo(that, userId, id, function(res) {
        let data = res.data;
        console.log(data, "晒照片-详情");
        if (data.code == 0) {
          let zplist = data.data.ZP;
          for (let i = 0; i < zplist.length; i++) {
            // 处理图片
            zplist[i].IMG = that.host.filehost + zplist[i].ID;
          }
          // console.log(zplist,'照片列表');
          that.csmc= data.data.CSMC;
          that.lpxy= data.data.GRJS;
          that.xm= data.data.XM;
          that.lxdh=data.data.DH;
        } else {
          that.Toastfn(data.msg, 2000, "");
        }
      });
    }
  },
  mounted() {
    let that = this;
    var userinfo = JSON.parse(sessionStorage.getItem("userinfo"));
    if (userinfo && userinfo.vipcode) {
      let userid = userinfo.vipcode;
      this.userid = userid;
      that.getDetail();
    } else {
      Toast({
        message: "您还不是会员，快去注册吧！",
        duration: 1600
      });
      setTimeout(function() {
        that.$router.push({ path: "/register", query: { type: "sign" } });
      }, 1600);
      return false;
    }
    this.$emit("footnavzt", false); //隐藏底布导航
  }
  // components: {
  //   Group,
  //   XAddress,
  // }
};
</script>

<style scoped lang="less">
.close {
  height: 40px;
  position: relative;
  margin-top: 0.4rem;
  img {
    position: absolute;
    right: 0.2rem;
    width: 40px;
    background-color: transparent;
  }
}
.fbbox {
  background-color: #ffffff;
  margin: 0.2rem;
  overflow: hidden;
  padding: 0.2rem;
  .fb-t {
    padding: 0.1rem 0.2rem;
    background-color: #f1f1f1;
    font-size: 18px;

    color: #333333;
  }
  .fb-list {
    color: #666666;
    // padding: 0.2rem;
    font-size: 14px;
    margin-bottom: 0.2rem;
    border: 1px solid #e6e6e6;
    .xzdq {
      padding: 0.2rem;
      border-bottom: 1px solid #f1f1f1;
      font-size: 16px;
    }
  }
}
//上传图片
#uploadImgBox {
  margin-bottom: 0.2rem;
  .uploadImage {
    width: 1.3rem;
    height: 1.3rem;
    margin-right: 0.1rem;
    display: inline-block;
    overflow: hidden;
    vertical-align: middle;
  }
  img {
    width: 100%;
    height: 100%;
  }
  .upTip {
    font-size: 0.32rem;
    color: #c6c5c5;
  }
}
// tjbtn
.tj {
  text-align: center;
  padding-bottom: 10px;
  .tjbtn {
    background-color: #ec6149;
    color: #ffffff;
    font-size: 0.32rem;
    padding: 0.2rem 0.7rem;
    border: 0;
    border-radius: 5px;
    display: inline-block;
    margin: 0 auto;
  }
}

// 上传图片
.upph {
  .chooseImg {
    padding-bottom: 0.2rem;
    /*border-bottom: 0.01rem solid #EEEEEE;*/
    p {
      font-size: 0.32rem;
      color: #c6c5c5;
    }
  }
  .chooseImg .head {
    display: flex;
    justify-content: space-between;
    padding: 0.2rem 0;
  }
  .chooseImg .head span {
    font-size: 0.32rem;
  }
  .chooseImg .head div {
    font-size: 0.3rem;
    color: #ccc;
  }
  .page-body-info {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  /*.hasPh {
				width: 2rem;
				height: 2rem;
				position: relative;
				margin: 0.1rem;
				border-radius: 0.1rem;
				img {
					width: 2rem;
					height: 2rem;
					border-radius: 0.1rem;
				}
			}*/
  .hasPh {
    width: 1.4rem;
    height: 1.4rem;
    margin: 0.1rem;
    position: relative;
    .phbox {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 1.4rem;
      overflow: hidden;
      border-radius: 0.1rem;
      img {
        width: 100%;
        /*height: 1.6rem;*/
        height: auto;
        border-radius: 0.1rem;
      }
    }
  }
  .hasPh .clear {
    position: absolute;
    right: -0.1rem;
    top: -0.1rem;
    width: 0.3rem;
    height: 0.3rem;
    border-radius: 50%;
    background-color: #ccc;
    color: #fff;
    font-size: 0.3rem;
    text-align: center;
    line-height: 0.3rem;
  }
  .chooseImg .chooseBtn {
    width: 1.4rem;
    height: 1.4rem;
    // border: 0.02rem solid #ddd;
    position: relative;
    margin: 0.1rem;
    overflow: hidden;
    border-radius: 0.1rem;
    input {
      width: 100%;
      height: 100%;
      opacity: 0;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 99;
    }
  }
}
</style>
